package netty.echo;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {

	private final int port;
	
	public EchoServer(int port) {
		this.port = port;
	}
	
	public void start() throws InterruptedException{
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(group)
			 .channel(NioServerSocketChannel.class)
			 .localAddress(new InetSocketAddress(port))
			 .childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					System.out.println("server init");
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(new EchoServerHandler());
					pipeline.addLast(new EchoSimpleChannelInboundHandler());
				}
			});
			ChannelFuture f = bootstrap.bind().sync();
//			f.addListener(new ChannelFutureListener() {
//                @Override
//                public void operationComplete(ChannelFuture future) throws Exception {
//                    System.out.println("ChannelFutureListener:" + future.channel().remoteAddress());
//                }
//            });
			System.out.println(getClass().getName() + " started and listen on " + f.channel().localAddress());
            Channel channel = f.channel();
            channel.closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		new EchoServer(8888).start();
	}
}